/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package tela;

import classPack.Chave;
import classPack.ClassesDAO;
import classPack.Conexao;
import classPack.Conversa;
import classPack.Usuario;
import java.util.HashMap;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

/**
 *
 * @author Eu
 */
public class Principal extends javax.swing.JFrame {

    public static Usuario logado = null;
    private Conexao conecta = null;
    public HashMap<String, Conversa> conversas = null;
    public HashMap<String, Usuario> usuarios = null;

    /**
     * Creates new form inicial
     */
    public Principal() {
        initComponents();
        conversas = ClassesDAO.getConversaArquivo(Conversa.class.getSimpleName());
        logado = ClassesDAO.getUsuarioArquivo("Logado");
        //usuarios = ClassesDAO.getUsuarioArquivo(Usuario.class.getSimpleName());
        usuarios = new HashMap<>();
        for (Conversa atual : conversas.values()) {
            usuarios.putAll(atual.getUsuarios());
        }
        while ((logado == null || logado.getNome().equals(""))) {
            logado = new Usuario(JOptionPane.showInputDialog(this, "Informar nome de usuario atual", "Informação", JOptionPane.INFORMATION_MESSAGE), Chave.getIpLocal());
        }
        logado.setOnline(true);
        logado.setAceito(true);
        logado.setBloqueado(false);
        conecta = Conexao.getInstance(this);
        conecta.Ligar();
        jLUsuario.setText(logado.getNome());
        conecta.entreiTodos();
        popularSelectList();
        changeLaf(this);
    }

    public static void changeLaf(JFrame frame) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
            e.printStackTrace();
        }
        SwingUtilities.updateComponentTreeUI(frame);
    }

    public void popularSelectList() {
        jListUsuarios.removeAll();
        jListGrupos.removeAll();
        jListNovoUsu.removeAll();

        DefaultListModel modelGrupos = new DefaultListModel();
        DefaultListModel modelUsu = new DefaultListModel();
        DefaultListModel modelNovoUsu = new DefaultListModel();

        for (Conversa atual : conversas.values()) {
            if (atual.isSingleUser()) {
                if (atual.isSingleUserOnline()) {
                    modelUsu.addElement(atual);
                }
            } else {
                modelGrupos.addElement(atual);
            }
        }
        for (Usuario atual : usuarios.values()) {
            if (!atual.isAceito()) {
                modelNovoUsu.addElement(atual);
            }
        }

        if (modelGrupos.isEmpty()) {
            modelGrupos.addElement("Nenhum...");
        }
        if (modelNovoUsu.isEmpty()) {
            modelNovoUsu.addElement("Nenhum...");
        }
        if (modelUsu.isEmpty()) {
            modelUsu.addElement("Nenhum...");
        }

        jListGrupos.setModel(modelGrupos);
        jListUsuarios.setModel(modelUsu);
        jListNovoUsu.setModel(modelNovoUsu);
    }

    public void Fechar() {
        System.out.println("Saindo...");
        conecta.saindoTodos();
        conecta.Desligar();
        limparTelas();
        ClassesDAO.gravaObjectArquivo(conversas, Conversa.class.getSimpleName());
        ClassesDAO.gravaObjectArquivo(logado, "Logado");
        //ClassesDAO.gravaObjectArquivo(usuarios, Usuario.class.getSimpleName());
    }

    public void limparTelas() {
        for (Conversa atual : conversas.values()) {
            atual.setJanela(null);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jPEsquerda = new javax.swing.JPanel();
        jPEsqTopo = new javax.swing.JPanel();
        jBSair = new javax.swing.JButton();
        jLUsuario = new javax.swing.JLabel();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPnlUsuarios = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jListUsuarios = new javax.swing.JList();
        jButton3 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jPnlGrupos = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jListGrupos = new javax.swing.JList();
        jButton4 = new javax.swing.JButton();
        jButton7 = new javax.swing.JButton();
        jPnlNovos = new javax.swing.JPanel();
        jButton2 = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        jListNovoUsu = new javax.swing.JList();
        jPBotton = new javax.swing.JPanel();
        txtNovoUser = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jTbPnConversas = new javax.swing.JTabbedPane();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jPEsquerda.setLayout(new java.awt.BorderLayout());

        jPEsqTopo.setLayout(new java.awt.BorderLayout());

        jBSair.setText("Sair");
        jBSair.setToolTipText("Clique em sair para sair");
        jBSair.setAutoscrolls(true);
        jBSair.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jBSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBSairActionPerformed(evt);
            }
        });
        jPEsqTopo.add(jBSair, java.awt.BorderLayout.CENTER);

        jLUsuario.setText("nome_usu");
        jLUsuario.setPreferredSize(new java.awt.Dimension(80, 14));
        jPEsqTopo.add(jLUsuario, java.awt.BorderLayout.PAGE_START);

        jPEsquerda.add(jPEsqTopo, java.awt.BorderLayout.PAGE_START);

        jPnlUsuarios.setLayout(new java.awt.BorderLayout());

        jListUsuarios.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jListUsuarios.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jListUsuariosMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jListUsuarios);

        jPnlUsuarios.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jButton3.setText("Bloquear");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        jPnlUsuarios.add(jButton3, java.awt.BorderLayout.PAGE_END);

        jButton6.setText("Grupo");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });
        jPnlUsuarios.add(jButton6, java.awt.BorderLayout.PAGE_START);

        jTabbedPane1.addTab("Usuarios", jPnlUsuarios);

        jPnlGrupos.setLayout(new java.awt.BorderLayout());

        jListGrupos.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jListGrupos.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jListGrupos.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jListGruposMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(jListGrupos);

        jPnlGrupos.add(jScrollPane2, java.awt.BorderLayout.CENTER);

        jButton4.setText("Sair");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        jPnlGrupos.add(jButton4, java.awt.BorderLayout.PAGE_END);

        jButton7.setText("Add Usu");
        jButton7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton7ActionPerformed(evt);
            }
        });
        jPnlGrupos.add(jButton7, java.awt.BorderLayout.PAGE_START);

        jTabbedPane1.addTab("Grupos", jPnlGrupos);

        jPnlNovos.setLayout(new java.awt.BorderLayout());

        jButton2.setText("Aceitar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPnlNovos.add(jButton2, java.awt.BorderLayout.PAGE_END);

        jListNovoUsu.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jListNovoUsu.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane3.setViewportView(jListNovoUsu);

        jPnlNovos.add(jScrollPane3, java.awt.BorderLayout.CENTER);

        jTabbedPane1.addTab("Novos Usu", jPnlNovos);

        jPEsquerda.add(jTabbedPane1, java.awt.BorderLayout.CENTER);

        getContentPane().add(jPEsquerda, java.awt.BorderLayout.LINE_START);

        jPBotton.setLayout(new java.awt.GridBagLayout());

        txtNovoUser.setMaximumSize(new java.awt.Dimension(45, 45));
        txtNovoUser.setMinimumSize(new java.awt.Dimension(45, 45));
        txtNovoUser.setPreferredSize(new java.awt.Dimension(120, 20));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        jPBotton.add(txtNovoUser, gridBagConstraints);

        jButton1.setText("Adicionar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        jPBotton.add(jButton1, gridBagConstraints);

        jButton5.setText("Atualizar");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });
        jPBotton.add(jButton5, new java.awt.GridBagConstraints());

        getContentPane().add(jPBotton, java.awt.BorderLayout.PAGE_END);
        getContentPane().add(jTbPnConversas, java.awt.BorderLayout.CENTER);
        jTbPnConversas.getAccessibleContext().setAccessibleDescription("");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jBSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBSairActionPerformed
        // TODO add your handling code here:
        Fechar();
        System.exit(0);
    }//GEN-LAST:event_jBSairActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        Fechar();
    }//GEN-LAST:event_formWindowClosing

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        if (!txtNovoUser.getText().equals("")) {
            Usuario novo = new Usuario(txtNovoUser.getText(), txtNovoUser.getText());
            novo.setAceito(true);
            novo.setOnline(false);
            usuarios.put(novo.getNome(), novo);
            conecta.solicitarUsu(novo);
            txtNovoUser.setText("");
            popularSelectList();
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jListUsuariosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListUsuariosMouseClicked
        if (evt.getClickCount() == 2 && (jListUsuarios.getSelectedValue() instanceof Conversa)) {
            Conversa selecionado = (Conversa) jListUsuarios.getSelectedValue();
            if (selecionado.getJanela() == null) {
                PanelConversa novaTela = new PanelConversa(jTbPnConversas, selecionado);
                selecionado.setJanela(novaTela);
                selecionado.montarTela();
                novaTela.setVisible(true);
            } else {
                PanelConversa telaConversa = selecionado.getJanela();
                telaConversa.mostrar();
            }
            jTbPnConversas.setSelectedComponent(selecionado.getJanela());
        }
    }//GEN-LAST:event_jListUsuariosMouseClicked

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        if (!jListNovoUsu.isSelectionEmpty() && (jListNovoUsu.getSelectedValue() instanceof Usuario)) {
            Usuario novoUsu = (Usuario) jListNovoUsu.getSelectedValue();
            novoUsu.setAceito(true);
            novoUsu.setOnline(true);
            conecta.aceitarUsu(novoUsu);
            Conversa conversaUsu = new Conversa(novoUsu.getNome());
            conversaUsu.addUsuario(novoUsu);
            conversaUsu.gerarNome();
            conversas.put(conversaUsu.getNome(), conversaUsu);
            popularSelectList();
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        // TODO add your handling code here:
        popularSelectList();
    }//GEN-LAST:event_jButton5ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        if (!jListUsuarios.isSelectionEmpty() && (jListUsuarios.getSelectedValue() instanceof Conversa)) {
            Conversa conversaSel = (Conversa) jListUsuarios.getSelectedValue();
            Usuario usuSelecionado = conversaSel.getSingleUser();
            if (usuSelecionado.isBloqueado()) {
                conecta.estouOnline(usuSelecionado);
            } else {
                conecta.estouOffLine(usuSelecionado);
            }
            usuSelecionado.toggleBloqueado();
            popularSelectList();
        }
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        if (!jListUsuarios.isSelectionEmpty() && (jListUsuarios.getSelectedValue() instanceof Conversa)) {
            String titulo = "";

            while (titulo.equals("")) {
                titulo = JOptionPane.showInputDialog(this, "Informe o titulo do grupo!", "Entrada de informações", JOptionPane.PLAIN_MESSAGE);
            }
            if (titulo != null) {
                Conversa nova = new Conversa(titulo, logado);
                for (Object conversa : jListUsuarios.getSelectedValuesList()) {
                    Conversa atualConv = (Conversa) conversa;
                    Usuario atual = atualConv.getSingleUser();
                    nova.addUsuario(atual);
                }
                nova.addUsuario(logado);
                nova.gerarNome();
                nova.setAceito(true);
                conversas.put(nova.getNome(), nova);
                conecta.enviarConviteGrupo(nova);
                popularSelectList();
            }
        }
    }//GEN-LAST:event_jButton6ActionPerformed

    private void jListGruposMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListGruposMouseClicked
        // TODO add your handling code here:
        if (evt.getClickCount() == 2 && (jListGrupos.getSelectedValue() instanceof Conversa)) {
            Conversa selecionado = (Conversa) jListGrupos.getSelectedValue();
            if (selecionado.getJanela() == null) {
                PanelConversa novaTela = new PanelConversa(jTbPnConversas, selecionado);
                selecionado.setJanela(novaTela);
                selecionado.montarTela();
                novaTela.setVisible(true);
            } else {
                PanelConversa telaConversa = selecionado.getJanela();
                telaConversa.mostrar();
            }
            conecta.solicitarAtualizacaoGrupo(selecionado);
            jTbPnConversas.setSelectedComponent(selecionado.getJanela());
        }
    }//GEN-LAST:event_jListGruposMouseClicked

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        // TODO add your handling code here:
        if (!jListGrupos.isSelectionEmpty() && (jListGrupos.getSelectedValue() instanceof Conversa)) {
            Conversa atual = (Conversa) jListGrupos.getSelectedValue();
            conecta.sairGrupo(atual);
            conversas.remove(atual.getNome());
            atual.getJanela().fecharJanela();
            popularSelectList();
        }
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
        // TODO add your handling code here:
        if (!jListUsuarios.isSelectionEmpty()
                && (jListUsuarios.getSelectedValue() instanceof Conversa)
                && !jListGrupos.isSelectionEmpty()
                && (jListGrupos.getSelectedValue() instanceof Conversa)) {
            Conversa conversaSel = (Conversa) jListGrupos.getSelectedValue();
            if (conversaSel.getAdmin().equals(logado)) {
                Usuario usuarioSel = ((Conversa) jListUsuarios.getSelectedValue()).getSingleUser();
                conversaSel.addUsuario(usuarioSel);
                conecta.incluirUsuarioGrupo(conversaSel, usuarioSel);
            }
        }
    }//GEN-LAST:event_jButton7ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Principal().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBSair;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JButton jButton7;
    private javax.swing.JLabel jLUsuario;
    private javax.swing.JList jListGrupos;
    private javax.swing.JList jListNovoUsu;
    private javax.swing.JList jListUsuarios;
    private javax.swing.JPanel jPBotton;
    private javax.swing.JPanel jPEsqTopo;
    private javax.swing.JPanel jPEsquerda;
    private javax.swing.JPanel jPnlGrupos;
    private javax.swing.JPanel jPnlNovos;
    private javax.swing.JPanel jPnlUsuarios;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTabbedPane jTabbedPane1;
    public javax.swing.JTabbedPane jTbPnConversas;
    private javax.swing.JTextField txtNovoUser;
    // End of variables declaration//GEN-END:variables
}
